// pages/cart/cart.js
const app = getApp();
import httpsUtils from '../../utils/https.js';
import calcUtils from '../../utils/calcUtil.js';
import myUtils from '../../utils/util.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartList: [],
    showeEmptyCart: false,
    showCart: true,
    guessLikeList: [],
    guessLikeLenght: 1,
    cartShow: false, //false 显示无商品 true显示登陆
    allCheckStatus: false, //全选状态
    cartID: "",
    checked: false,
    checked1: false,
    totalMoney: '0.00'
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 获取购物车商品
   */
  getCarGoods: function (e) {
    var that = this;
    httpsUtils.getData({
      _url: app.globalData._url + '/goodsCar/selectGoodsCarList2',
      data: '',
    }, function (json) {
      if (json.success == false && json.code == 'OVERTIME') {
        that.setData({
          cartShow: false,
        })
        that.getMyLikeGoods();
      } else if (json.data && json.data != null) {

        //默认所有不选中
        for (let shop of json.data) {
          shop.checkStatus = false;
          for (let goods of shop.goodsList) {
            goods.checkStatus = false;
          }
        }

        that.setData({
          cartList: json.data,
          showeEmptyCart: false,
          showCart: true,
          cartShow: true,
        })
      } else {
        that.setData({
          cartShow: true,
        })
        that.getMyLikeGoods();
      }
    });
  },
  /**
   *猜你喜欢列表
   */
  getMyLikeGoods: function (e) {
    var that = this;
    httpsUtils.getData({
      _url: app.globalData._url + '/goods/selectGoodsList?goodsType=1',
      data: {},
    }, function (json) {
      if (json.data && json.success) {
        that.setData({
          guessLikeList: json.data.list,//猜你喜欢列表
          guessLikeLenght: json.data.total,
        })
      }
      that.setData({
        showeEmptyCart: true,
        showCart: false
      })
    })
  },
  /**
   * 多选框后选中处理
   */
  checkChange: function (e) {
    var that = this;
    var cartList = that.data.cartList;
    var checkType = e.currentTarget.dataset.type; //选中类型：car-单件商品选中，shop-店铺选中，all-全选
    var checkId = e.currentTarget.dataset.id;//选中id

    //初始化全选勾选
    var allCheckStatus = !that.data.allCheckStatus;

    //单商品选中
    if (checkType == 'car') {
      for (let shop of cartList) {
        //初始化店铺勾选
        shop.checkStatus = true;
        for (let goods of shop.goodsList) {
          if (checkId == goods.goodsCar.id) {
            goods.checkStatus = !goods.checkStatus;
          }
          //存在单个商品未选中的情况，则店铺不勾选
          if (!goods.checkStatus) {
            shop.checkStatus = false;
          }
        }

        //存在店铺未选中，则全选不勾选
        if (!shop.checkStatus) {
          allCheckStatus = false;
        }
      }
    }

    //店铺选中/未选中
    if (checkType == 'shop') {
      for (let shop of cartList) {
        if (checkId == shop.id) {
          shop.checkStatus = !shop.checkStatus;
          for (let goods of shop.goodsList) {
            goods.checkStatus = shop.checkStatus;
          }
        }

        //存在店铺未选中，则全选不勾选
        if (!shop.checkStatus) {
          allCheckStatus = false;
        }
      }
    }

    //全选
    if (checkType == 'all') {
      for (let shop of cartList) {
        shop.checkStatus = allCheckStatus;
        for (let goods of shop.goodsList) {
          goods.checkStatus = allCheckStatus;
        }
      }
    }

    that.setData({
      cartList: cartList,
      allCheckStatus: allCheckStatus
    })

    //计算商品金额
    that.calcGoods();
  },

  //计算商品金额
  calcGoods: function () {
    var that = this;
    var cartList = that.data.cartList;
    var totalMoney = 0.00;
    for (let shop of cartList) {
      for (let goods of shop.goodsList) {
        if (goods.checkStatus) {
          totalMoney = calcUtils.add(calcUtils.mul(goods.goodsCar.goodsNumber, goods.goodsCar.packRate).toFixed(2), totalMoney);
        }
      }
    }
    that.setData({
      totalMoney: totalMoney.toFixed(2)
    })
  },

  /**
   * 删除单商品
   */
  deleteNumber: function (e) {
    var that = this;
    var delId = e.currentTarget.dataset.id;//选中id
    wx.showModal({
      content: '确定删除该商品吗？',
      success: function (res) {
        if (res.confirm) {
          httpsUtils.getData({
            _url: app.globalData._url + '/goodsCar/delGoodsCarByGoodsIdOnPC?ids=' + delId,
            data: {}
          }, function (json) {
            if (json.success) {
              //更新商品
              that.getCarGoods();
              wx.showToast({
                title: '删除成功',
              })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  /**
   * 去支付
   */
  countMoney: function () {
    
    var that = this;
    var cartList = that.data.cartList;
    var toPayCartList = [];

    //查找选中的购物车
    for (let shop of cartList) {
      if (shop.status == 4 && shop.checkStatus){
        wx.hideLoading();
        wx.showModal({
          title: '提示',
          content: '存在已下架商品，无法结算',
          showCancel: false
        })
        return;
      }
      var goodsList = [];
      for (let goods of shop.goodsList) {
        if (goods.checkStatus) {
          var goodStyle = [];//商品样式
          for (let goodsStyle of goods.myStockList) {
            goodStyle.push(goodsStyle.colour.colourName + " " + goodsStyle.size.sizeName + "*" + goodsStyle.saleNum);
          }
          goods.goodStyle = myUtils.concatStr(goodStyle, ",");

          goodsList.push(goods);
        }
      }
      if (goodsList.length > 0) {
        if (shop.status == 4 ) {
          wx.hideLoading();
          wx.showModal({
            title: '提示',
            content: '存在已下架商品，无法结算',
            showCancel: false
          })
          return;
        }
        shop.goodsList = goodsList;
        toPayCartList.push(shop);
      }
    }

    if (toPayCartList.length > 0) {
      wx.setStorageSync("payCarList", toPayCartList);
      wx.setStorageSync("addressId", '');
      wx.navigateTo({
        url: '../commitOrder/commitOrder'
      })
    } else {
      wx.hideLoading();
      wx.showModal({
        title: '提示',
        content: '请选中至少一个商品去结算',
        showCancel: true
      })
    }
    wx.hideLoading();
  },
  /**
   * 修改商品
   */
  modifyGoods:function(e){
    var goodsId = e.currentTarget.dataset.goodsId;//选中id
    var goodsType = e.currentTarget.dataset.goodsType;//商品类型
    if(goodsType != 1){
      wx.showModal({
        title: '修改提示',
        content: '打折商品不允许修改数量',
        showCancel:false
      })
      return;
    }else{
      wx.navigateTo({
        url: '../addCart/addCart?id=' + goodsId,
      })
    }

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.setData({
      allCheckStatus: false
    })
    //获取购物车商品
    that.getCarGoods();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      cartList: [],
      showeEmptyCart: false,
      showCart: true,
      guessLikeList: [],
      guessLikeLenght: 1,
      cartShow: false, //false 显示无商品 true显示登陆
      allCheckStatus: false, //全选状态
      cartID: "",
      checked: false,
      checked1: false,
      totalMoney: '0.00'
    })
    this.onShow();
    wx.stopPullDownRefresh(); 
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /*事件函数*/
  lookAround: function () {
    wx.switchTab({
      url: '../index/index',
      success: function () {

      },
      fail: function () {
        wx.showToast({
          title: '浏览失败',
        })
      }
    })

  },
  lookAround1: function () {
    wx.navigateTo({
      url: '../wxLogin/wxLogin?type=5&isTab=false',
      success: function () {
      },
      fail: function () {
        wx.showToast({
          title: '登陆失败',
        })
      }
    })
  },
  checkAddCartChange: function (e) {
    var checkboxItems = this.data.goodList;
    var values = e.detail.value;
    for (var i = 0; i < checkboxItems.length; ++i) {
      checkboxItems[i].checked = false;
      for (var j = 0; j < values.length; ++j) {
        if (checkboxItems[i].isbn == values[j]) {
          checkboxItems[i].checked = true;
          break;
        }
      }
    }
    var checkAll = false;
    if (checkboxItems.length == values.length) {
      checkAll = true;
    }

    this.setData({
      'goodList': checkboxItems,
      'checkAll': checkAll
    });
    this.calculateTotal();
  },
  getData: function (params, cb) {
    wx.request({
      url: params._url,
      data: params.data,
      method: 'GET',
      header: { "Content-Type": "application/json;charset=UTF-8", 'Cookie': 'JSESSIONID=' + app.globalData.token },
      success: function (res) {
        if (res.statusCode == 200) {
          typeof cb === 'function' && cb(res.data)

        }
      },
      fail: function () {
      },
      complete: function () {
      }
    })
  }

})